package com.midea.ai.air.ui.chat;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.midea.ai.air.R;
import com.midea.ai.air.common.ActionBarFragement;
import com.midea.ai.air.common.BaseFragment;
import com.midea.ai.air.common.BuildConfig;
import com.midea.ai.air.common.Constant;
import com.midea.ai.air.data.ResultModel;
import com.midea.ai.air.utils.L;
import com.midea.ai.air.utils.Machine;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ouyangdi on 2015/12/30.
 */
public class ChatFragment extends BaseFragment {
    FrameLayout mBarLayout;
    ListView mChatList;
    Button mBtnSend;
    EditText mInputMsg;
    ImageView mIvSwitch;
    Button mBtnSpeak;
    RelativeLayout mTextContainer;

    List<ChatMsgModel> mChatMsgs;
    ChatlistAdapter mAdapter;
    ActionBarFragement mBarFragment;
    boolean mIsInputText = true; //当前是否是文本输入(true:文本输入 false:语音输入)

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_chat, container, false);
        initData();
        initViews(view);
        initListener();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getManager().getCurrentIndex() == 3) {
            Machine.initSystemBar(getActivity(), true);
            L.i("JUNE", "ChatFragmemt onResume");
        }
    }

    private void initData() {
        mChatMsgs = new ArrayList<>();
        mChatMsgs.add(new ChatMsgModel("有事启奏，无事退朝。朕今天没吃早餐", ChatMsgModel.Type.RECEIVE));
        mAdapter = new ChatlistAdapter(getActivity(), mChatMsgs);
    }

    private void initViews(View view) {

        mBarLayout = (FrameLayout) view.findViewById(R.id.bar_parent);
        ViewGroup.LayoutParams LP = mBarLayout.getLayoutParams();
        LP.height = Constant.getTopMargin() + getResources().getDimensionPixelSize(R.dimen.height_44dp);
        mBarLayout.setLayoutParams(LP);

        mBarFragment = (ActionBarFragement) getChildFragmentManager().findFragmentById(R.id.bar_fragment);
        mBarFragment.getTitle().setText("语音");

        mChatList = (ListView) view.findViewById(R.id.lv_chat);
        mChatList.setAdapter(mAdapter);

        mBtnSend = (Button) view.findViewById(R.id.btn_send);
        mInputMsg = (EditText) view.findViewById(R.id.text_send);
        mIvSwitch = (ImageView)view.findViewById(R.id.iv_switch);
        mBtnSpeak = (Button)view.findViewById(R.id.btn_speak);
        mTextContainer = (RelativeLayout)view.findViewById(R.id.text_input_container);
    }

    private String toJson(String msg) throws JSONException {
        JSONObject object = new JSONObject();
        object.put("userId", "1");
        object.put("familyId", "1");
        object.put("roomId", "1");
        object.put("type", "1");
        object.put("data", msg);
        return object.toString();
    }

    private void sendMsg(String msg) {
        try {
            post(BuildConfig.URL_SENC_CHAT_MSG, toJson(msg));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        Log.i("JUNE", "asyncExecute url=" + url);
        Log.i("JUNE", "asyncExecute json=" + resultModel.getJson());
        if (url.contains(BuildConfig.URL_SENC_CHAT_MSG)) {
            String msg = resultModel.getResult();
            return msg;
        }
        return super.asyncExecute(url, resultModel);
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        Log.i("JUNE", "onFailure url=" + url);
        Log.i("JUNE", "onFailure json=" + resultModel.getJson());
        super.onFailure(url, resultModel);
        Toast.makeText(getContext(), resultModel.getErrMsg(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(String url, Exception e) {
        Log.i("JUNE", "onError url=" + url);
        Log.i("JUNE", "onError Exception=" + e.getMessage());
        super.onError(url, e);
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) {
        super.onSucceed(url, resultModel);
        Log.i("JUNE", "onSucceed url=" + url);
        Log.i("JUNE", "onSucceed json=" + resultModel.getJson());
        if (url.contains(BuildConfig.URL_SENC_CHAT_MSG)) {
            mChatMsgs.add(new ChatMsgModel((String) resultModel.getDataModel(), ChatMsgModel.Type.RECEIVE));
            mAdapter.notifyDataSetChanged();
            mChatList.setSelection(mChatMsgs.size() - 1);
        }
    }

    private void initListener() {
        mBtnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sendMsg = mInputMsg.getText().toString();
                if (sendMsg.isEmpty()) {
                    Toast.makeText(getActivity(), "发送消息不能为空", Toast.LENGTH_LONG).show();
                } else {
                    sendMsg(sendMsg);
                    mChatMsgs.add(new ChatMsgModel(sendMsg, ChatMsgModel.Type.SEND_TEXT));
                    mAdapter.notifyDataSetChanged();
                    mChatList.setSelection(mChatMsgs.size() - 1);
                    mInputMsg.setText("");
                }
            }
        });

        mIvSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mIsInputText) {
                    mIsInputText = false;
                    mIvSwitch.setImageResource(R.drawable.air_voice_keyboard);
                    mBtnSpeak.setVisibility(View.VISIBLE);
                    mTextContainer.setVisibility(View.GONE);
                } else {
                    mIsInputText = true;
                    mIvSwitch.setImageResource(R.drawable.air_voice_keyboard_mic);
                    mBtnSpeak.setVisibility(View.GONE);
                    mTextContainer.setVisibility(View.VISIBLE);
                }
            }
        });

        mBtnSpeak.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mBtnSpeak.setText(getResources().getString(R.string.chat_up_stop));
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    mChatMsgs.add(new ChatMsgModel("", ChatMsgModel.Type.SEND_VOICE));
                    mAdapter.notifyDataSetChanged();
                    mChatList.setSelection(mChatMsgs.size() - 1);
                    mBtnSpeak.setText(getResources().getString(R.string.chat_press_speak));
                }
                return false;
            }
        });

        mInputMsg.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                //得到InputMethodManager的实例
                if (imm.isActive()) {
                    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        });

        mChatList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mChatList.requestFocus();
                return false;
            }
        });
    }
}
